package com.mhl.client;


import android.graphics.Bitmap;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.mhl.campuscabinet.R;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class QiNiuUtil {
    // 单实例模型
    private static QiNiuUtil instance;
    private Configuration config;
    private UploadManager manager;
    private QiNiuUtil() {

    }
    public static QiNiuUtil getInstance() {
        if(instance == null) {
            instance = new QiNiuUtil();
            instance.config = new Configuration(Region.autoRegion());
            instance.manager = new UploadManager(instance.config);
        }
        return instance;
    }

    // AK
    private final String AK = "gllUD3Ik4X7BaXw44GBY6jKfqI9K5qLhNCFZ7uf8";
    // SK
    private final String SK = "La3cQhn95ATO4pACyogVtHWxeFvkLejMEwHh1vVv";
    // bucket
    private final String bucket = "campus-cabinet";
    // 获取token
    private String getToken() {
        Auth auth = Auth.create(AK, SK);
        return auth.uploadToken(bucket);
    }
    // 上传
    public String uploadToQiNiu(Bitmap bitmap, String key) {
        String webHash = "";
        String token = getToken();
        try {
            Response response = manager.put(getBitmapByte(bitmap), key, token);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
            webHash = putRet.hash;
        } catch (QiniuException e) {
            e.printStackTrace();
        }
        return webHash;
    }
    // 将bitmap转为二进制数组
    public byte[] getBitmapByte(Bitmap bitmap){
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
        try {
            out.flush();
            out.close();
            } catch (IOException e) {
            e.printStackTrace();
            }
        return out.toByteArray();
    }
    // 将二进制数组转为bitmap

}
